package com.hzh.SparkStreaming

import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo5RDDToDS {

  def main(args: Array[String]): Unit = {

    /**
     * 创建环境
     *
     */

    val spark: SparkSession = SparkSession
      .builder()
      .config("spark.sql.shuffle.partitions", 1)
      .master("local[2]")
      .appName("Demo4DSToRDDAndDF")
      .getOrCreate()

    import spark.implicits._

    val sc: SparkContext = spark.sparkContext

    val ssc = new StreamingContext(sc,Durations.seconds(5))

    val sscDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    /**
     * transform：每隔5秒 传入一个RDD，在里面使用RDD的api处理数据，处理完成之后在返回一个RDD
     *
     */
    val resultRDD: DStream[(String, Int)] = sscDS.transform((rdd: RDD[String]) => {
      val countRDD: RDD[(String, Int)] = rdd.flatMap(_.split(","))
        .map((_, 1))
        .reduceByKey(_ + _)

      //处理完成之后返回一个RDD，返回的rdd构建成新的DStream
      countRDD


    })




  }

}
